<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box"></div>
    <script>

        let ajax = {
            get:function(url,data,callBack){
                let x = new XMLHttpRequest();
                let str = Object.keys(data).map(item=>`${item}=${data[item]}&`).join('').slice(0,-1);
                x.open('get',url+'?'+str);
                x.send();
                x.responseType='json';
                x.onreadystatechange=function(){
                    if(x.readyState === 4 && x.status === 200){
                        callBack(x.response);
                    }
                }
            },
            post:function(url,data,callBack){
                let x = new XMLHttpRequest();
                x.open('post',url);
                let str = Object.keys(data).map(item=>`${item}=${data[item]}&`).join('').slice(0,-1);
                console.log(str); //name=post数据&age=66
                x.setRequestHeader('content-type','application/x-www-form-urlencoded');
                x.send(str);
                x.responseType='json';
                x.onreadystatechange=function(){
                    if(x.readyState === 4 && x.status === 200){
                        callBack(x.response);
                    }
                }
            }
        }

        let box = document.querySelector('#box');
        window.onload = function(){

            // ajax.get('http://localhost/ajaxserver',{name:"王哥",age:"22"},function(data){
            //     console.log(data);
            //     // let obj = JSON.parse(data);
            //     box.innerHTML = `姓名：${data.name}，年龄：${data.age}`;
            // })

            ajax.post('http://localhost/ajaxserverpost',{name:"post数据",age:"66"},function(data){
                // console.log(data);
                box.innerHTML = `姓名：${data.name}，年龄：${data.age}`;
            })
        }
    </script>
</body>
</html>